package com.weipai.springboot.module.service.impl;

import com.weipai.springboot.enums.DemandStatus;
import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.*;
import com.weipai.springboot.model.api.PageResult;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.module.dao.*;
import com.weipai.springboot.module.mapper.DemandMapper;
import com.weipai.springboot.module.service.DemandService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 曹朋飞
 * @Date: 2018/08/06 17:59
 */
@Service
public class DemandServiceImpl implements DemandService {

    private static final Logger log = LoggerFactory.getLogger(BrandServiceImpl.class);

    @Autowired
    DemandDao demandDao;
    @Autowired
    AdminDao adminDao;
    @Autowired
    ArtisanDao artisanDao;
    @Autowired
    CustomerDao customerDao;
    @Autowired
    SystemDao systemDao;

    //更改需求的状态--0未接单，1客服介入，2已完成，3已驳回, 4 待处理
    @Override
    public Response changeStatus(String id, Integer status) {
        Response response = new Response();
        if (1 == demandDao.updateStatus(id, status)) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //查询数据
    @Override
    public List<Demand> selectAllByDemand(String demandCategoryId) {
        return demandDao.selectAllByDemand(demandCategoryId);
    }

    //查看需求详情
    @Override
    public Response getDemandById(String id) {
        Response response = new Response();
        List<Map<String,Object>> demand=demandDao.getDemandByArtisan(id);

//        Demand demand = demandDao.getDemandById(id);
        if (null != demand) {
            response.setCode(RetCode.SUCCESS);
            response.put("data", demand);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //根据需求状态分页查询
    @Override
    public Response selectDemandByStatus(Integer page, Integer size, String draw, Integer demandStatus) {
        List<Demand> list = demandDao.selectDemandByStatus(demandStatus, (page - 1) * size, size);
        Integer totalNum = demandDao.countDemandByStatus(demandStatus);
        PageResult<Demand> pageList = new PageResult<>(list, page, size, totalNum, draw);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    //需求列表
    @Override
    public Response demandListByCity(Integer status, Integer page, Integer size) {

        Integer start = (page - 1) * size;
        List<Map<String, Object>> list = demandDao.demandListByCity(start, size, status);
        Integer totalNum = demandDao.demandListAmountByCity(status);
        PageResult<Map<String, Object>> pageList = new PageResult<>(list, page, size, totalNum, "");
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    //根据发布人 id  查需求订单
    @Override
    public Response demandListByCustomer(String customerId, Integer status, Integer page, Integer size) {
        Integer start = (page - 1) * size;
        List<Map<String, Object>> list = demandDao.demandListByCustomer(start, size, customerId, status);

        Integer totalNum = demandDao.demandListAmountByCustomer(customerId, status);
        PageResult<Map<String, Object>> pageList = new PageResult<>(list, page, size, totalNum, "");
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    // 根据技工 id  查需求订单
    @Override
    public Response demandListByArtisanId(String artisanId, Integer status, Integer page, Integer size) {
        Integer start = (page - 1) * size;
        List<Map<String, Object>> list = demandDao.demandListByArtisanId(start, size, artisanId, status);

        Integer totalNum = demandDao.demandListAmountByArtisanId(artisanId, status);
        PageResult<Map<String, Object>> pageList = new PageResult<>(list, page, size, totalNum, "");
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    /**
     * 定时修改技工可提现金额
     *
     * @throws Exception
     */
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void artisanMoney() throws Exception {
        //查看技工收益表数据,将超过7天的订单改为不可修改订单
        //应该用获取收益的时间+7天的时间如果《现在的时间，满足修改订单状态的条件
        List<Map<String, Object>> cashMoney = artisanDao.getCanCashMoney();
        for (int i = 0; i < cashMoney.size(); i++) {
            String customer_id = (String) cashMoney.get(i).get("customerId");
            int hcashMoney1 = Integer.parseInt(String.valueOf(cashMoney.get(i).get("hcashMoney")));
            Customer customer = customerDao.getCustomerById(customer_id);
            int hcashMoney2 = customer.getHcashMoney();
            int hcashMoney = hcashMoney1 + hcashMoney2;
            customerDao.updateByHaveCashMoney(hcashMoney, customer_id);
        }
        artisanDao.updateStatus();
    }


    @Override
    public Response handlePending(String demandId, String name, String loginName) {
        Response response = new Response();
        Demand demand = demandDao.getDemandById(demandId);
        if (demand.getDemandStatus() == DemandStatus.PENDING.getStatus()) {
            //判断客服账号是否正确
            Admin admin = adminDao.getAdminByLoginName(loginName);
            if (admin == null) {
                response.setCode(RetCode.DEMAND_SERVICE_STAFF_ERROR);
                return response;
            }
            Demand newDemand = new Demand();
            newDemand.setDemandId(demandId);
            newDemand.setDemandStatus(DemandStatus.PROCESSING.getStatus());
            newDemand.setServiceName(name);
            newDemand.setServiceJobNumber(loginName);
            demandDao.update(newDemand);
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    @Override
    public Response saveArtisanInfo(String demandId, String name, String mobile, int amount) {
        Artisan artisan = artisanDao.getArtisanByMobile(mobile);
        Response response = new Response();
        Demand demand = demandDao.getDemandById(demandId);
        if (artisan == null) {
            response.setCode(RetCode.DEMAND_ARTISAN_INFO_ERROR);
        } else if (demand.getDemandStatus() == DemandStatus.PROCESSING.getStatus()) {
            Demand newDemand = new Demand();
            newDemand.setDemandId(demandId);
            newDemand.setArtisanId(artisan.getArtisanId());
            newDemand.setArtisanName(name);
            newDemand.setArtisanMobile(mobile);
            newDemand.setDemandStatus(demand.getDemandStatus());
            newDemand.setDemandMoney(amount);
            newDemand.setServiceTime(new Date()); //客服介入时间
            demandDao.update(newDemand);
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response complete(String demandId) {
        Response response = new Response();
        Demand demand = demandDao.getDemandById(demandId);
        if (demand.getDemandStatus() == DemandStatus.SUCCESS.getStatus()) {
            Demand newDemand = new Demand();
            newDemand.setDemandId(demandId);
            newDemand.setDemandStatus(DemandStatus.COMPLETED.getStatus());
            demandDao.update(newDemand);
            //增加技工收益,平台是否分成,比率是多少
            int amount = demand.getDemandMoney();
            addAlternative(demand);
            addCustomCashMoney(demand);
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.NONSUPPORT);
        }
        return response;
    }

    //更新 需求信息
    @Override
    public Response update(Demand demand) {
        return null;
    }


    //增加技工接单数
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void addAlternative(Demand demand) {
        Artisan artisan = artisanDao.getArtisanById(demand.getArtisanId());
//        Artisan artisan = new Artisan();
//        artisan.setArtisanId(demand.getArtisanId());
        artisan.setAlternative(artisan.getAlternative() + 1);
        artisanDao.updateByPrimaryKey(artisan);
    }

    //增加技工收益
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void addCustomCashMoney(Demand demand) {
        Map<String, Object> commissionRate = systemDao.getCommissionRateByType(1);
        //double rate = (100 - Integer.valueOf(commissionRate.getOrDefault("commission_rate", 0) + "")) / 100.00;
//        int rate = Integer.valueOf(commissionRate.get("commissionRate").toString());
        BigDecimal rate = new BigDecimal(Integer.parseInt(commissionRate.get("commissionRate").toString())).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN);
        Artisan artisan = artisanDao.getArtisanById(demand.getArtisanId());
        Customer artisanCustomer = customerDao.getCustomerById(artisan.getCustomerId());
//        BigDecimal money = new BigDecimal(rate).multiply(new BigDecimal(demand.getDemandMoney())).divide(new BigDecimal(100));
//        BigDecimal money = new BigDecimal(rate).multiply(new BigDecimal(demand.getDemandMoney()));
        BigDecimal money = new BigDecimal(demand.getDemandMoney()).multiply(rate);
        artisanCustomer.setCashMoney(artisanCustomer.getCashMoney() + money.intValue());
        //技工收益
        ArtisanEarings earings = new ArtisanEarings();
        earings.setArtisanId(artisan.getArtisanId());
        earings.setCustomerId(artisanCustomer.getCustomerId());
        earings.setDemandId(demand.getDemandId());
        earings.setMoney(money.intValue());
        earings.setType(1);
        earings.setMoneyStatus(0);
        artisanDao.saveArtisanEarings(earings);
        customerDao.updateByPrimaryKey(artisanCustomer);
    }


}
